/**   
 * All rights Reserved, Designed By MiGu  
 * Copyright:    Copyright(C) 2016-2020  
 * Company       MiGu  Co., Ltd.
*/
package com.migu.spms.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.migu.spms.common.StringUtil;
import com.migu.spms.constant.Constant;
import com.migu.spms.dao.entity.ChangeHistoryCriteria;
import com.migu.spms.dao.entity.FunctionRequireCriteria;
import com.migu.spms.dao.entity.FunctionRequireDO;
import com.migu.spms.dao.entity.RequireTypeTreeCriteria;
import com.migu.spms.dao.entity.RequireTypeTreeDO;
import com.migu.spms.dao.inf.IFunctionRequireDO;
import com.migu.spms.dao.inf.IRequireTypeTreeDO;
import com.migu.spms.dao.inf.ISubParentRequireDO;
import com.migu.spms.service.data.User;
import com.migu.spms.service.inf.IChangeHistoryService;
import com.migu.spms.service.inf.IRequireTypeTreeService;
import com.migu.spms.utils.CodeCreateUtil;
import com.migu.spms.utils.PropertiesCopyUtil;
import com.migu.spms.utils.exception.ServiceException;
import com.migu.spms.webapi.data.GetTypeTreeRequest;
import com.migu.spms.webapi.data.MoveRequireTypeTreeRequest;
import com.migu.spms.webapi.data.RequireTypeTreeRequest;

/**   
 * RequireTypeTreeServiceImpl类
 * 项目名称:  SPMS功能需求
 * 包名称:    com.migu.spms.service.impl   
 * 类名称:    RequireTypeTreeServiceImpl.java
 * 类描述:    
 * 创建人:    wcr   
 * 创建时间:  2017年6月19日 上午10:02:34   
 */
@Transactional
@Service("requireTypeTreeServiceImpl")
public class RequireTypeTreeServiceImpl implements IRequireTypeTreeService {
    private static Logger logger = LoggerFactory.getLogger(RequireTypeTreeServiceImpl.class);
    @Resource(name = "IRequireTypeTreeDO")
    IRequireTypeTreeDO requireTypeTreeDO;

    @Resource(name = "IFunctionRequireDO")
    private IFunctionRequireDO functionRequireDao;

    @Resource(name = "ISubParentRequireDO")
    private ISubParentRequireDO subParentRequireDao;

    @Resource(name = "changeHistoryServiceImpl")
    private IChangeHistoryService changeHistoryService;

    @Override
    public List<RequireTypeTreeDO> selectRequireTypeTreeList(GetTypeTreeRequest typeTreeRequest) throws Exception {
        if (null == typeTreeRequest.getProjectId()) {
            logger.error(CodeCreateUtil.createLogMessage("RequireTypeTreeServiceImpl.selectRequireTypeTreeList",
                    "查询分类树[参数中项目id为空]"));
            throw new ServiceException("项目id不能为空");
        }
        RequireTypeTreeCriteria requireTree = new RequireTypeTreeCriteria();
        requireTree.setProjectId(typeTreeRequest.getProjectId());
        List<RequireTypeTreeDO> treeList = requireTypeTreeDO.selectRequireTypeTreeList(requireTree);
        FunctionRequireCriteria functionRequireCriteria = new FunctionRequireCriteria();
        functionRequireCriteria.setProjectId(typeTreeRequest.getProjectId());
        int totalNumber = functionRequireDao.queryNumberByProjectId(typeTreeRequest.getProjectId());
        for (RequireTypeTreeDO re : treeList) {
            if (re.getId() == 1L) {
                re.setTypeCount(totalNumber);
            } else {
                int count = functionRequireDao.selectCountByTypeTree(Long.toString(re.getId()).split(","),
                        typeTreeRequest.getProjectId());
                /*String typeTreeList = requireTypeTreeDO.getTypeTreeList(Long.toString(re.getId()));
                String[] split = typeTreeList.split(",");
                if(split.length>1){

                    count = functionRequireDao.selectCountByTypeTree(split,
                            typeTreeRequest.getProjectId());
                }*/
                re.setTypeCount(count);
            }
        }
        return treeList;
    }

    @Override
    public void insertRequireTypeTree(RequireTypeTreeRequest res, User user) throws Exception {
        RequireTypeTreeCriteria requireTypeTreeCriteria=new RequireTypeTreeCriteria();
        requireTypeTreeCriteria.setProjectId(res.getProjectId());
        requireTypeTreeCriteria.setName(res.getName());
        //判断单前项目下是否有该分类
        List<RequireTypeTreeDO> requireTypeTree=requireTypeTreeDO.selectRequireTypeTreeList(requireTypeTreeCriteria);
        if(null==requireTypeTree || requireTypeTree.size()==0){
        	RequireTypeTreeCriteria criteria = PropertiesCopyUtil.parse(res, RequireTypeTreeCriteria.class);
        	criteria.setProjectId(res.getProjectId());
        	criteria.setUrl(Constant.typeTree.URL);
            criteria.setCreateUid(Integer.toString(user.getUserId()));
            criteria.setCreateUname(user.getUserName());
            criteria.setCreateTime(new Date());
            criteria.setRemark(res.getRemark());
        	requireTypeTreeDO.insertSelective(criteria);
        }else{
        	throw new ServiceException("当前项目下已创建分类名【"+requireTypeTreeCriteria.getName()+"】请更换分类名称");
        }
        	
    }

    @Override
    public void deleteRequireTypeTree(RequireTypeTreeRequest res) throws Exception {
        if (res.getId().equals(Constant.typeTree.ONE) || res.getId().equals(Constant.typeTree.TWO)) {
            throw new ServiceException("主分类不可删除！");
        } else {
            RequireTypeTreeDO typeTree = requireTypeTreeDO.selectByPrimaryKey(Long.valueOf(res.getId()));
            if (null == typeTree) {
                throw new ServiceException("分类不存在！");
            } else {
                RequireTypeTreeCriteria record = new RequireTypeTreeCriteria();
                record.setPid(Long.valueOf(res.getId()));
                record.setProjectId(res.getProjectId());
                List<RequireTypeTreeDO> sonList = requireTypeTreeDO.selectRequireTypeTreeList(record);
                if (null != sonList && sonList.size() > 0) {
                    throw new ServiceException("不可删除，存在子分类！");
                } else {
                    FunctionRequireCriteria fun = new FunctionRequireCriteria();
                    fun.setRequireTypeId(Long.valueOf(res.getId()));
                    fun.setProjectId(res.getProjectId());
                    List<FunctionRequireDO> funList = functionRequireDao.selectListByCriteria(fun);
                    if (null != funList && funList.size() > 0) {
                        String treeId = "";
                        for (FunctionRequireDO fd : funList) {
                            treeId += Long.toString(fd.getRequireTypeId()) + ",";
                        }
                        RequireTypeTreeDO typeTwo = requireTypeTreeDO
                                .selectByPrimaryKey(Long.valueOf(Constant.typeTree.TWO));
                        functionRequireDao.updateTypeByTreeId(treeId, Long.toString(typeTwo.getId()),
                                typeTwo.getName());
                    }
                }
            }
            requireTypeTreeDO.deleteByPrimaryKey(Long.valueOf(res.getId()));
        }
    }

    @Override
    public void updateRequireTypeTree(RequireTypeTreeCriteria criteria) throws Exception {
    	RequireTypeTreeCriteria requireTypeTreeCriteria=new RequireTypeTreeCriteria();
        requireTypeTreeCriteria.setProjectId(criteria.getProjectId());
        requireTypeTreeCriteria.setName(criteria.getName());
        //判断单前项目下是否有该分类
        List<RequireTypeTreeDO> requireTypeTree=requireTypeTreeDO.selectRequireTypeTreeList(requireTypeTreeCriteria);
        if(null==requireTypeTree||requireTypeTree.size()==0){
        	requireTypeTreeDO.updateByPrimaryKeySelective(criteria);
        	functionRequireDao.updateTypeByTreeId(Long.toString(criteria.getId()), Long.toString(criteria.getId()),
        			criteria.getName());
        }else{
        	throw new ServiceException("当前项目下已存在分类名【"+requireTypeTreeCriteria.getName()+"】请更换分类名称");
        }
    }

    @Override
    public void moveTypeTreeByRequire(MoveRequireTypeTreeRequest res, User user) throws Exception {
        if (null == res.getFunctionRequireIds() || null == res.getTypeTreeId()
                || StringUtil.isEmpty(res.getTypeTreeName())) {
            throw new ServiceException("参数为空，请重试！");
        }
        // List<String> updateIds = new ArrayList<String>();
        // String[] ids = res.getFunctionRequireIds().split(",");
        // for (String id : ids) {
        // // 查询所有所属子父分类ID
        // String childRequirementIds =
        // subParentRequireDao.getSubParentRequireList(id.toString());
        // String[] requirementArray = childRequirementIds.split(",");
        // Collections.addAll(updateIds, requirementArray);
        // }
        // for (String idUpdate : updateIds) {
        // FunctionRequireDO oldFun =
        // functionRequireDao.selectByPrimaryKey(Long.valueOf(idUpdate));
        // FunctionRequireCriteria newFun = PropertiesCopyUtil.parse(oldFun,
        // FunctionRequireCriteria.class);
        // newFun.setRequireTypeId(res.getTypeTreeId());
        // newFun.setRequireTypeName(res.getTypeTreeName());
        // functionRequireDao.updateByPrimaryKeySelective(newFun);
        //
        // ChangeHistoryCriteria history = new ChangeHistoryCriteria();
        // history.setCreateId(Long.valueOf(user.getUserId()));
        // history.setCreateName(user.getUserName());
        // history.setCreateTime(new Date());
        // history.setIsDetails("0");
        // history.setIsPermit("0");
        // history.setIsBaseLine(Integer.toString(oldFun.getIsBaseLine()));
        // history.setFunctionRequireId(oldFun.getId());
        // history.setBaselineVersion(oldFun.getBaselineVersion());
        // history.setRemark(
        // "修改分类===原分类：" + oldFun.getRequireTypeName() + " ===修改为：" +
        // newFun.getRequireTypeName() + "===");
        // changeHistoryService.inesertChangeHistoryCommon(history, null, null);
        // }
        String idStr = "";
        for (Long functionRequireId : res.getFunctionRequireIds()) {
            List<FunctionRequireDO> functionRequireDOs = functionRequireDao
                    .queryRequireListByPrimaryKey(functionRequireId);
            if (null != functionRequireDOs && functionRequireDOs.size() > 0) {
                
                for (FunctionRequireDO functionRequireDO : functionRequireDOs) {
                    if(functionRequireDO.getIsSubRequire() == 0){
                        idStr += functionRequireDO.getId()+",";
                    }
                }
            }
        }
        String[] split = idStr.split(",");
        String subParentRequireList = "";
        if(null != split && split.length>0){
            for (String str : split) {
                subParentRequireList += subParentRequireDao.getSubParentRequireList(str) + ",";
            }
        }
        String[] subStr = subParentRequireList.split(",");
        if(null != subStr && subStr.length > 0){
            for (String str : subStr) {
                FunctionRequireDO oldFun = functionRequireDao.selectByPrimaryKey(Long.valueOf(str));
                FunctionRequireCriteria functionRequireCriteria = new FunctionRequireCriteria();
                functionRequireCriteria.setId(Long.valueOf(str));
                functionRequireCriteria.setRequireTypeId(res.getTypeTreeId());
                functionRequireCriteria.setRequireTypeName(res.getTypeTreeName());
                functionRequireDao.updateByPrimaryKeySelective(functionRequireCriteria);
                ChangeHistoryCriteria history = new ChangeHistoryCriteria();
                history.setCreateId(Long.valueOf(user.getUserId()));
                history.setCreateName(user.getUserName());
                history.setCreateTime(new Date());
                history.setIsDetails("0");
                history.setIsPermit("0");
                history.setIsBaseLine(Integer.toString(oldFun.getIsBaseLine()));
                history.setFunctionRequireId(oldFun.getId());
                history.setBaselineVersion(oldFun.getBaselineVersion());
                history.setRemark("修改分类===原分类：" + oldFun.getRequireTypeName() + " ===修改为："
                        + functionRequireCriteria.getRequireTypeName() + "===");
                changeHistoryService.inesertChangeHistoryCommon(history, null, null);
            }
        }
    }
}
